package com.ssm.juc;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * Semaphore 基本使用测试
 */
@Slf4j
public class SemaphoreTest {

    // 线程池
    private static ExecutorService executorService
            = Executors.newFixedThreadPool(10);
    // 限制只有 5 个线程能够同时获取锁
    private static Semaphore semaphore = new Semaphore(5);

    public static void main(String[] args) throws InterruptedException {
        for (; ; ) {
            Thread.sleep(100);
            executorService.submit(() -> exec());
        }
    }

    public static void exec() {
        try {
            semaphore.acquire(1);
            log.info("执行 exec 方法");
            TimeUnit.SECONDS.sleep(2);
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
            semaphore.release(1);
        }
    }
}